package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.heima.article.dao.ApArticleConfigDao;
import com.heima.article.dao.ApArticleContentDao;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.entity.ApArticle;
import com.heima.article.dao.ApArticleDao;
import com.heima.article.service.ApArticleService;
import com.heima.model.article.entity.ApArticleConfig;
import com.heima.model.article.entity.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.enums.AppArticleInfo;
import com.heima.utils.common.SnowflakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 文章基础信息表(ApArticle)表服务实现类
 *
 * @author makejava
 * @since 2022-04-16 22:06:01
 */
@Service("apArticleService")
public class ApArticleServiceImpl implements ApArticleService {
    @Resource
    private ApArticleDao apArticleDao;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    private ApArticleConfigDao apArticleConfigDao;

    @Autowired
    private ApArticleContentDao apArticleContentDao;

    @Autowired
    private ApArticleFreemarkerService apArticleFreemarkerService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ApArticle queryById(Long id) {
        return this.apArticleDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param apArticle   筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @Override
    public Page<ApArticle> queryByPage(ApArticle apArticle, PageRequest pageRequest) {
        long total = this.apArticleDao.count(apArticle);
        return new PageImpl<>(this.apArticleDao.queryAllByLimit(apArticle, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param apArticle 实例对象
     * @return 实例对象
     */
    @Override
    public ApArticle insert(ApArticle apArticle) {
        this.apArticleDao.insert(apArticle);
        return apArticle;
    }

    /**
     * 修改数据
     *
     * @param apArticle 实例对象
     * @return 实例对象
     */
    @Override
    public ApArticle update(ApArticle apArticle) {
        this.apArticleDao.update(apArticle);
        return this.queryById(apArticle.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.apArticleDao.deleteById(id) > 0;
    }

    //添加文章
    @Override
    public ResponseResult save(ArticleDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApArticle apArticle = new ApArticle();
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        ApArticleContent apArticleContent = new ApArticleContent();
        BeanUtils.copyProperties(dto, apArticle);
        Long newsId = dto.getNewsId();
        ApArticle IndexapArticle = apArticleDao.queryByNewsId(newsId);
        if (IndexapArticle == null) {
            long id = snowflakeIdWorker.nextId();//雪花算法
            apArticle.setId(id);
            //1.添加文章基础信息表
            apArticle.setLikes(0);
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticleDao.insert(apArticle);
            //2.添加文章配置表
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setEnable(1);
            apArticleConfig.setIsDelete(0);
            apArticleConfig.setIsComment(1);
            apArticleConfig.setIsForward(1);
            apArticleConfigDao.insert(apArticleConfig);
            //3.添加文章内容表
            apArticleContent.setContent(dto.getContent());
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContentDao.insert(apArticleContent);
        } else {
            //修改 1.文章基础表
            apArticle.setId(IndexapArticle.getId());
            apArticleDao.update(apArticle);
            //2.文章内容表
            apArticleContent.setArticleId(IndexapArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentDao.update(apArticleContent);
        }
        //将生成模板静态网页保存到minio
        String staticUrl = apArticleFreemarkerService.buildArticle2Minio(apArticle.getId(), dto.getContent());
        if (StringUtils.isEmpty(staticUrl)){
            throw new RuntimeException("生成静态网页出错");
        }
        //添加静态url数据
        apArticle.setStaticUrl(staticUrl);
        apArticleDao.update(apArticle);
        //创建app端es对应实体类,每次新增或者修改文章数据,需要把数据同步到es库中
        AppArticleInfo appArticleInfo = new AppArticleInfo();
        BeanUtils.copyProperties(apArticle,appArticleInfo);
        appArticleInfo.setContent(dto.getContent());
        String resultAppArticleInfo = JSON.toJSONString(appArticleInfo);
        //将最新的对象发送到topic中,由搜索服务来进行监听
        kafkaTemplate.send("add.articleInfo.topic",resultAppArticleInfo);
        return ResponseResult.okResult(apArticle.getId());
    }


    @Override
    public ResponseResult queryMoreAndNew(ArticleHomeDto dto) {
        //如果类型
        if (StringUtils.isEmpty(dto.getSize())) {
            dto.setSize(10);
        }
        List<ApArticle> list = apArticleDao.queryMoreAndNew(dto);
        return ResponseResult.okResult(list);
    }
}
